<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="学员类型" prop="user_type">
            <el-select v-model="queryParams.user_type" filterable placeholder="学员类型">
              <el-option label="线上" value="线上" />
              <el-option label="线下" value="线下" />
            </el-select>
          </el-form-item>
          <el-form-item prop="name" label="姓名">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="phone" label="电话">
            <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable size="small" />
          </el-form-item>
          <el-form-item label="学员来源" prop="from">
            <el-select v-model="queryParams.from" placeholder="学员来源" clearable size="small">
              <el-option v-for="dict in source" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学员等级" prop="user_label">
            <el-select v-model="queryParams.user_label" filterable placeholder="学员等级">
              <el-option label="普通" value="普通" />
              <el-option label="VIP" value="VIP" />
              <el-option label="SVIP" value="SVIP" />
            </el-select>
          </el-form-item>
          <el-form-item label="地区" prop="province">
            <el-select v-model="queryParams.province" filterable placeholder="请选择地址">
              <el-option v-for="item in regionList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="exportClick">
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              size="mini"
              :disabled="multiple"
              @click="operation({}, 3)"
            >结业
            </el-button>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20"> -->
        <!-- <el-col :span="5" :xs="24">
            <div class="head-container">
              <el-tree
                ref="tree"
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>-->
        <!-- <el-col :span="24"> -->
        <el-table
          v-loading="loading"
          :data="dataList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column type="index" header-align="center" width="50" label="序号" fixed="left" align="center" />
          <el-table-column label="姓名" width="70" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="手机号" prop="phone" width="108" />
          <el-table-column label="身份证号" prop="id_card" :show-overflow-tooltip="true" />
          <el-table-column label="就读院校" prop="order_count" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.college_id ? scope.row.college.colleges_name : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报考省份" prop="province_name">
            <template slot-scope="scope">
              <span>{{ scope.row.province ? scope.row.province_region.name : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="升本年份" prop="shen_ben_time" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.shen_ben_time, '{y}-{m}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学员等级" prop="user_label" />
          <el-table-column label="学员类型" prop="user_type" />
          <el-table-column label="学员来源" prop="invitation" />
          <el-table-column label="学员状态" prop="buy_status">
            <template slot-scope="scope">
              {{ typeFormat(buyStatus, scope.row.buy_status) }}
            </template>
          </el-table-column>
          <el-table-column label="学员科别" prop="ke_bie" />
          <el-table-column label="学员去向" prop="follow_direction">
            <template slot-scope="scope">
              {{ typeFormat(followDirection, scope.row.follow_direction) }}
            </template>
          </el-table-column>
          <el-table-column label="注册时间" prop="createdAt" sortable="custom" width="155">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="170" fixed="right" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <router-link :to="`/admin/sys-teaching/student/view/${scope.row.id}`">
                    <el-button size="mini" type="text" icon="el-icon-view">查看</el-button>
                  </router-link>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="operation(scope.row, scope.row.buy_status === 4 ? 2 : 4)"
                  >
                    {{ scope.row.buy_status === 4 ? '正式' : '退学' }}
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="operation(scope.row, 3)">结业
                  </el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- </el-col>
        </el-row> -->
      </el-card>
      <el-dialog title="支付时间" :visible.sync="open" width="600px">
        <el-form ref="exportForm" :model="exportForm" :rules="rules" label-width="120px">
          <el-form-item label="订单提交时间" prop="dateRange">
            <el-date-picker
              v-model="exportForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </template>
  </BasicLayout>
</template>

<script>
import { listStudent, changeUserStatus, updateBuyStatus, exportExcel } from '@/api/admin/sys-student'
import { getRegion } from '@/api/admin/sys-course'
// import { treeselect } from '@/api/admin/sys-dept'

// import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'SysStudentManage',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: null,
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      // dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 表单参数
      form: {},
      exportForm: {},
      rules: {
        dateRange: [
          { required: true, message: '选择时间', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        from: undefined,
        user_type: undefined,
        user_label: undefined,
        province: undefined,
        start_time: undefined,
        end_time: undefined
      },
      source: [
        { label: '注册', value: 1 },
        { label: '学生邀请', value: 2 },
        { label: '教师邀请', value: 3 }
      ],
      regionList: [],
      followDirection: [
        { label: '正常', value: 0 },
        { label: '流失不再为其提供服务', value: 1 },
        { label: '放弃', value: 2 },
        { label: '成为游客', value: 3 }
      ],
      buyStatus: [
        { label: '游客', value: 1 },
        { label: '正式学员', value: 2 },
        { label: '结业', value: 3 },
        { label: '退学', value: 4 }
      ]
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    getRegion({ parent_id: 1 }).then(res => {
      this.regionList = res.data
    })
    // this.getTreeselect()
  },
  methods: {
    getList() {
      this.loading = true
      listStudent({
        ...this.queryParams
      }).then(
        response => {
          this.dataList = response.data.list.map(item => {
            if (item.teach_recommender) {
              return { ...item, invitation: '教师推荐' }
            } else if (item.recommender) {
              return { ...item, invitation: '学员推荐' }
            } else {
              return { ...item, invitation: '注册' }
            }
          })
          this.total = response.data.count
          this.loading = false
        }
      )
    },
    // 参数系统内置字典翻译
    typeFormat(column, val) {
      return this.selectDictLabel(column, val)
    },
    /** 查询部门下拉树结构 */
    // getTreeselect() {
    //   treeselect().then(response => {
    //     this.deptOptions = response.data
    //   })
    // },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = '/' + data.id + '/'
      this.getList()
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '2' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.name + '"用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return changeUserStatus(row)
        })
        .then(() => {
          this.msgSuccess(text + '成功')
        })
        .catch(function() {
          row.status = row.status === '2' ? '1' : '2'
        })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    operation(value, text) {
      const ids = (value?.id && [value?.id]) || this.ids
      this.$confirm('是否确认操作的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return updateBuyStatus({
            buy_status: text,
            ids
          })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() { })
    },
    cancel() {
      this.open = false
    },
    exportClick() {
      this.open = true
    },
    submitForm() {
      this.$refs['exportForm'].validate(valid => {
        if (valid) {
          const { dateRange } = this.exportForm
          exportExcel({
            start_time: dateRange[0] || undefined,
            end_time: dateRange[1] || undefined
          })
          this.open = false
          this.exportForm = {}
        }
      })
    }
  }
}
</script>
